package com.wonders;

import javax.servlet.*;
import javax.servlet.annotation.WebListener;
import java.util.EnumSet;
import java.util.HashMap;

@WebListener
public class MyRegisterListener implements ServletContextListener {

    /**
     * This method is called when the servlet context is
     * initialized(when the Web application is deployed).
     * You can initialize servlet context related data here.
     *
     * @param sce
     */
    public void contextInitialized(ServletContextEvent sce) {
        // 获取上下文ServletContext
        ServletContext servletContext = sce.getServletContext();

        // 动态注册Listener
        servletContext.addListener("com.noredister.MyListener");

        // 动态注册Servlet
        ServletRegistration.Dynamic dynamic = servletContext.addServlet("my-servlet", "com.noredister.MyServlet");
        dynamic.addMapping("/MyServlet");
        dynamic.setInitParameters(new HashMap<String, String>() {{
            put("key1", "value1");
            put("key2", "value2");
        }});

        // 动态注册Filter
        FilterRegistration.Dynamic dynamic1 = servletContext.addFilter("my-filter", "com.noredister.MyFilter");
        // 拦截所有的默认请求，该拦截器将在所有已注册的拦截器之后执行
        dynamic1.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");

        // 动态注册Listener[注意注册的Listener不能是ServletContextListener]
        servletContext.addListener("com.noredister.MyListener");
    }


}
